package com.think.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;

/**
 * <p>
 * AntiSqlFilter 是一个 J2EE Web 应用程序过滤器，可以保护 Web 组件免受 SQL 注入黑客攻击
 * </p>
 *
 * @author: xwj
 * @data: 2019-04-06
 */
public class AntiSqlFilter {
    /**
     * 敏感关键字数组
     */
    private static final String[] KEY_WORDS = {";", "\"", "\'", "/*", "*/", "--", "exec",
            "select", "update", "delete", "insert",
            "alter", "drop", "create", "shutdown"};

    /**
     * 封装方法：过滤数组中的包含在keyWords（自定义数组）的关键字
     *
     * @param oldValues 过滤数组
     * @author xwj
     * @data 2019/4/6
     * @return java.lang.String[]
     */
    public static String[] getSafeValues(String[] oldValues) {
        if (ArrayUtils.isNotEmpty(oldValues)) {
            String[] newValues = new String[oldValues.length];
            for (int i = 0; i < oldValues.length; i++) {
                newValues[i] = getSafeValue(oldValues[i]);
            }
            return newValues;
        }
        return null;
    }

    /***
     * 基础方法：过滤字符串中的包含在keyWords（自定义数组）的关键字
     *
     * @param oldValue  过滤字符串
     * @author xwj
     * @data 2019/4/6
     * @return java.lang.String
     */
    private static String getSafeValue(String oldValue) {
        StringBuilder sb = new StringBuilder(oldValue);
        String lowerCase = oldValue.toLowerCase();
        for (String keyWord : KEY_WORDS) {
            int x;
            while ((x = lowerCase.indexOf(keyWord)) >= 0) {
                if (keyWord.length() == 1) {
                    sb.replace(x, x + 1, " ");
                    lowerCase = sb.toString().toLowerCase();
                    continue;
                }
                sb.deleteCharAt(x + 1);
                lowerCase = sb.toString().toLowerCase();
            }
        }
        return sb.toString();
    }
}
